package com.tungse.proxy_dome;

import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

// 1. 定义接口
interface UserService {
    void addUser(String username);
    void deleteUser(String username);
    String getUserInfo(String username);
}

// 2. 实现接口的实际类
class UserServiceImpl implements UserService {
    @Override
    public void addUser(String username) {
        System.out.println("添加用户: " + username);
    }

    @Override
    public void deleteUser(String username) {
        System.out.println("删除用户: " + username);
    }

    @Override
    public String getUserInfo(String username) {
        return "用户信息: " + username;
    }
}

// 3. 实现InvocationHandler接口
class LoggingHandler implements InvocationHandler {
    private final Object target;
    private StringBuilder logArea;
    
    public LoggingHandler(Object target, StringBuilder logArea) {
        this.target = target;
        this.logArea = logArea;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String log = "调用方法: " + method.getName() + ", 参数: " + Arrays.toString(args);
        logArea.append(log + "\n");
        System.out.println(log);
        
        // 实际方法调用
        Object result = method.invoke(target, args);
        
        log = "方法返回: " + result;
        logArea.append(log + "\n");
        System.out.println(log);
        
        return result;
    }
}